package com.xyb.service;

import com.xyb.config.exception.MyException;
import com.xyb.dao.WebUserDao;
import com.xyb.entity.StatusCode;
import com.xyb.entity.WebUser;
import com.xyb.utils.IdUtils;
import com.xyb.vo.RegisterUserVo;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class RegisterService {
    @Resource
    private WebUserDao webUserDao;
    @Resource
    private IdUtils idUtils;
    @Resource
    private PasswordEncoder passwordEncoder;

    public void selectIphoneIsRegistered(RegisterUserVo vo) {
        WebUser webUser = webUserDao.selectWebUserByIphoneNo(vo.getIphoneNo());
        if (webUser != null) {  //手机号已经注册
            throw new MyException(StatusCode.PHONE_HAS_REGISTERED_EXCEPTION);
        }
    }

    public String insertUser(RegisterUserVo vo) {
        //创建用户
        long nextId = idUtils.nextId();
        WebUser user = WebUser.builder()
                .userId(nextId)
                .userName(vo.getUserNickName())
                .userNickName(vo.getUserNickName())
                .iphoneNo(vo.getIphoneNo())
                .email(vo.getEmail())
                .userPwd(passwordEncoder.encode(vo.getUserPwd()))
                .headPortraitUrl("https://img0.baidu.com/it/u=2129874889,2770063179&fm=26&fmt=auto")
                .status(1)
                .createTime(new Date())
                .build();
        webUserDao.insertWebUser(user);
        return "success";
    }
}
